<?

// *****************************************************************************
// ****************         COPIED AND MODIFIED                   **************
// ****************         FROM interface.php                    **************
// *****************************************************************************


/**
* create ast_config (used by editor)
*
* @param stringArray $lines
* @param string      $filename
* @return 1 
*
*/

function createAstConfigZap($lines,$filename) {

  global $db;

  $cat_metric=-1;
  $var_metric=0;

  // remove all the old records about this $filename
  $qry="DELETE FROM ast_config WHERE filename='$filename'";
  $res=$db->Execute($qry);

  // Ciclo attraverso l'array, si visualizzerà il sorgente come html ed i numeri di linea
  foreach($lines as $line_num => $line) {
    $line=trim($line);
    if ($line{0}=="") continue;
    if ($line{0}==";") {
      $comment=str_replace("\"","'",trim(substr(trim($line),1)));
      $var_name="";
      $var_val="";
      $commented=1;
      $var_metric++;
      //echo "<span color='green'>$comment</span><br>";
    } else {
      $commented="0";
      if ($line{0}=="[") {
        $arr_comm=split(";",trim($line));
        $category=substr(trim($arr_comm[0]),1,strlen(trim($arr_comm[0]))-2);
        $zsection=$category; // Added for Zapata
        $comment=trim($arr_comm[1]);
        //echo "<h1>$category</h1>";
        if ($filename == "zapata.conf") {
          if ($zsection == "trunkgroups") {
            $cat_metric = 2;
            $var_metric=-1;
          } else { // put all channels in cat_metric 1
            $cat_metric = 1;
          }
        } else {   // any other file
          $cat_metric++;
          $var_metric=-1;
        }
        continue;
      } else {
        $arr=split("=|=>",$line);
        $var_name=trim($arr[0]);
        unset($arr[0]);
        $arr_comm=split(";",trim(implode("=", $arr)));
        $var_val=trim($arr_comm[0]);
        $comment=trim($arr_comm[1]);
        $var_metric++;
        //echo "<b>$var_name</b> || <i>$var_val</i><br>";
      }  
    }
    $var_name=str_replace("\"","\\\"",$var_name);
    $var_val=str_replace("\"","\\\"",$var_val); 
          
//    $qry="INSERT INTO ast_config (cat_metric,var_metric,commented,filename,category,var_name,var_val,comment)";
//    $qry.="VALUES ($cat_metric,$var_metric,$commented,\"$filename\",\"$category\",\"$var_name\",\"$var_val\",\"$comment\")";

    if ($filename == "zapata.conf") {
      if ($category == "trunkgroups")
        $zsection="trunkgroups";
      if ($category != "trunkgroups")
        $category="channels";
      $qry="INSERT INTO ast_config (cat_metric,var_metric,commented,filename,category,var_name,var_val,comment,zsection)";
      $qry.="VALUES ($cat_metric,$var_metric,$commented,\"$filename\",\"$category\",\"$var_name\",\"$var_val\",\"$comment\",\"$zsection\")";
    } else {
      $qry="INSERT INTO ast_config (cat_metric,var_metric,commented,filename,category,var_name,var_val,comment)";
      $qry.="VALUES ($cat_metric,$var_metric,$commented,\"$filename\",\"$category\",\"$var_name\",\"$var_val\",\"$comment\")";
    }

    $res=$db->Execute($qry);
    if ($res==false) error_log ("Error: $qry"); 
    
  }
  return 1;
}


/**
* View ast_config zsection
*
* @param string $f (filename)
* @return $ret (ast_config section)
*
*/

function viewAstConfigZap($f) {

  global $db;

  $qry="SELECT DISTINCT filename FROM ast_config WHERE filename='$f'";
  $res=$db->Execute($qry);
  while ($arr=$res->FetchRow()) {
    $filename=$arr["filename"];

  //$qry="SELECT DISTINCT category FROM ast_config WHERE filename='$filename' ORDER BY cat_metric";
    $qry="SELECT DISTINCT category, zsection FROM ast_config WHERE filename='$filename' ORDER BY cat_metric desc, var_metric asc";
    $res2=$db->Execute($qry);
    while ($arr=$res2->FetchRow()) {
      $category=$arr["category"];
      $zsection=$arr["zsection"];
      $ret.= "\n";
      if ($zsection != "")
        $ret.= "[".$zsection."]\n";
      else
        $ret.= "[".$category."]\n";

    //$qry="SELECT * FROM ast_config WHERE filename='$filename' AND category='$category' ORDER BY cat_metric desc, var_metric asc";
      $qry="SELECT * FROM ast_config WHERE filename='$filename' AND category='$category' AND zsection='$zsection' ORDER BY cat_metric desc, var_metric asc";
      $res3=$db->Execute($qry);
      while ($arr=$res3->FetchRow()) {
        $var_name=$arr["var_name"];
        $var_val=$arr["var_val"];
        $comment=$arr["comment"];
        $commented=$arr["commented"];
//        if ($var_name!="" and $commented!=1)
//          if ($var_name=='channel') $ret.="$var_name => $var_val";
//          else $ret.= "$var_name = $var_val";
//        if ($comment!="" and $var_name!="") $ret.= "\t ;$comment";
        if ($var_name!="" and $commented!=1) {
          if ($var_name=='channel') {
            $ret.= "$var_name => $var_val";
          } else { 
            $ret.= "$var_name = $var_val";
          }
        }
        if ($var_name!="" and $commented==1) {
          if ($var_name=='channel') {
            $ret.= "; $var_name => $var_val";
          } else {
            $ret.= "; $var_name = $var_val";
          }
        }
        if ($comment!="" and $var_name!="") $ret.= "\t ;$comment";
        if ($comment!="" and $var_name=="") $ret.= ";$comment";
        $ret.="\n";
      }
    }
  }
  return $ret;
}

/**
* Put a new zsection into ast_config
*
* @param string  $file
* @param string  $context
* @param string  $var
* @param string  $var_data
* @param string  $comment
* @param integer $commented
* @param string  $zsection
* @return $astconfig_id
* 
*/

function putAstConfigZap($file,$context,$var,$var_data,$comment="",$commented=0,$zsection="") {

  global $db;

  $context  = string2sql($context);
  $var      = string2sql($var);
  $var_data = string2sql($var_data);
  $comment  = string2sql($comment);

  // delete the old groups_default section
  // Todo: fix this properly later on when merging the code with putAstConfig

  $qry="DELETE FROM `ast_config` WHERE `filename` = 'zapata.conf' AND `category` = 'channels' AND `zsection` = ''";
  $db->Execute($qry); 
    
  // check if any other same ast_config entry is already into the table

  $qry="SELECT * FROM ast_config WHERE filename=\"$file\" AND category=\"$context\" AND var_name=\"$var\" AND var_val=\"$var_data\" AND zsection=\"$zsection\"";
  $res=$db->Execute($qry);
  if ($res->RecordCount()>0) {
    $arr=$res->FetchRow();
    return $arr["id"];  
  }
  
  // calculate the var_metric

//$qry="SELECT * FROM ast_config WHERE filename='$file' and category='$context'";
  $qry="SELECT * FROM ast_config WHERE filename='$file' and category='$context' AND zsection='$zsection'";
  $res=$db->Execute($qry);
  $count=$res->RecordCount();
  $arrCat=$res->FetchRow();
  if ($count>0) {
//  $qry="SELECT MAX(var_metric) as maxvar FROM ast_config WHERE filename='$file' and category='$context'";
    $qry="SELECT MAX(var_metric) as maxvar FROM ast_config WHERE filename='$file' and category='$context' AND zsection = '$zsection'";
    $res=$db->Execute($qry);
    $arr=$res->FetchRow();
    $var_metric=$arr["maxvar"]+1;
    $cat_metric=$arrCat["cat_metric"];
  } else {
    $qry="SELECT MAX(cat_metric) as maxcat FROM  ast_config WHERE  filename='$file'";
    $res=$db->Execute($qry);
    $arr=$res->FetchRow();
    $cat_metric=$arr["maxcat"]+1;    
    $var_metric=0;
  }    

  //$var=string2sql($var);
  //$var_data=string2sql($var_data); 
  //$comment=string2sql($comment); 
    
//$qry="INSERT INTO ast_config (cat_metric,var_metric,commented,filename,category,var_name,var_val,comment)";
//$qry.="VALUES($cat_metric,$var_metric,$commented,\"$file\",\"$context\",\"$var\",\"$var_data\",\"$comment\")";
  $qry="INSERT INTO ast_config (cat_metric,var_metric,commented,filename,category,var_name,var_val,comment,zsection)";
  $qry.="VALUES($cat_metric,$var_metric,$commented,\"$file\",\"$context\",\"$var\",\"$var_data\",\"$comment\",\"$zsection\")";
  $res=$db->Execute($qry);
  $astconfig_id=$db->Insert_ID();

  // Sort zapata channel section 

  If ($file == "zapata.conf" && $context == "channels" ) {

    $cat_metric = 1; // All channels are in cat_metric 1
    $var_metric = 0;

    $qry="SELECT `id` FROM ast_config WHERE filename='zapata.conf' AND category='channels' ORDER BY zsection, var_metric asc";
    $res=$db->Execute($qry);
    while ($arr=$res->FetchRow()) {
      $id = $arr["id"];
      $qry="UPDATE `ast_config` SET `cat_metric` = '$cat_metric', `var_metric` = '$var_metric' WHERE `filename` = 'zapata.conf' AND `id` = '$id'";
      $db->Execute($qry);
      $var_metric++;
    }
  }
  return $astconfig_id;
}


/**
* Deletes a zsection in ast_config
*
* @param string $file
* @param string $category
* @param string $var_name=""
* @param string $var_val=""
* @param string $zsection=""
* @return $res
*/

function delAstConfigZap($file,$category,$var_name="",$var_val="",$zsection="") {
  global $db;

//$qry="DELETE FROM ast_config WHERE filename=\"$file\" AND category like \"$category\" ";
  $qry="DELETE FROM ast_config WHERE filename=\"$file\" AND category like \"$category\" AND zsection=\"$zsection\" ";
  if ($var_name!="")  $qry.=" AND var_name  like \"".$var_name."\"";
  if ($var_val!="") $qry.=" AND var_val like \"".$var_val."\"";
  $res=$db->Execute($qry);

  return $res;
}

?>
